class dryCommon extends HTMLElement{
    constructor(){
        super();
        var that = this;
        var url = get("url");/*数据请求接口地址*/
        var iframeUrl = get("iframeUrl");/*文件组件选择按钮点击时需要打开的iframe网页地址*/
        var ref = get("ref");/*容器id*/
        var role = get("role");/*组件类型*/
        var scene = get("scene", "none");/*场景,数据源在头部自动插入一个不同的数据项,取值none|top|all|select*/
        var callback = get("callback");/*回调函数*/
        var label = get("label");/*表单文字说明*/
        var help = get("help");/*帮助文字*/
        var tip = get("tip");/*提示文字*/
        var value = get("value");/*表单值*/
        var name = get("name");/*表单名称*/
        var vclass = get("class");/*表单样式*/
        var placeholder= get("placeholder");/*表单占位文字*/
        var variable = get("variable");/*数据来源变量名*/
        var submit = get("submit");/*提交按钮文字*/
        var reset = get("reset");/*重置按钮文字*/
        var checked = get("checked");/*开关的打开状态*/
        var openText = get("openText");/*开关的打开文字*/
        var closeText = get("closeText");/*开关的关闭文字*/
        var block = get("block", 0);/*是否块布局(单独一行)*/
        var verify = get("verify");/*lay-verify的值*/
        var html = [];/*组件html代码*/
        var data = null;/*原始数据*/
        var list = [];/*数据列表*/
        var x = {};/*相关函数挂载对象*/

        function get(name, theDefault = "")
        {
            if(that.hasAttribute(name)){
                return that.getAttribute(name);
            }
            return theDefault;
        }

        function $$(id)
        {
            return document.getElementById(id);
        }

        function contain(string, element)
        {
            var theList = string.split(",");
            for(var i = 0;i < theList.length;i++){
                if(theList[i] == element){
                    return true;
                }
            }
            return false;
        }

        function getUnique()
        {
            var d = new Date();
            var temp = Math.random() + "";
            return "g_" + d.getTime() + "_" + temp.substr(2);
        }
        
        function toFormData(data)
        {
            var fd = new FormData();
            for(var key in data){
                fd.append(key, data[key]);
            }
            return fd;
        }
        
        function post(url, data, successCallback, failCallback)
        {
            function innerSuccess(response)
            {
                if(response.ok == true && response.status == 200){
                    response.json().then(function(json){
                        successCallback(json);
                    });
                }
            }
            
            function innerFail(response)
            {
                failCallback(response);
            }
            
            fetch(url, {method: "post", body: data}).then(innerSuccess).catch(innerFail);
        }

        function direct()
        {
            if(role == "selectOnly"){
                x["selectHtml"]();
            }
            else if(role == "dateOnly"){
                x["dateHtml"]();
            }
            else if(role == "timeOnly"){
                x["timeHtml"]();
            }
            else if(role == "datetimeOnly"){
                x["datetimeHtml"]();
            }
            else{
                createHtml();
            }
            doFinish();
        }

        function success(response)
        {
            if(response.ok == true && response.status == 200){
                response.json().then(function(json){
                    data = json;
                    list = json.data.list;
                    list = insert(list);
                    data.data.list = list;
                    direct();
                });
            }
        }

        function fail(response)
        {
            console.log(response);
        }

        function insert(theList)
        {
            if(scene == "top"){
                theList.unshift({"key": "0", "text": "作为顶级", "class": ""});
            }
            else if(scene == "all"){
                theList.unshift({"key": "all", "text": "全部", "class": ""});
            }
            else if(scene == "select"){
                theList.unshift({"key": "-1", "text": "请选择", "class": ""});
            }
            return theList;
        }

        x.inputHtml = function()
        {
            var v = name;
            if(verify != ""){
                v = verify;
            }
            html.push(`<input type="text" lay-verify="${v}" class="layui-input ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.dateHtml = function()
        {
            html.push(`<input type="text" lay-verify="${name}" class="layui-input date ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.timeHtml = function()
        {
            html.push(`<input type="text" lay-verify="${name}" class="layui-input time ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.datetimeHtml = function()
        {
            html.push(`<input type="text" lay-verify="${name}" class="layui-input datetime ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.passwordHtml = function()
        {
            html.push(`<input type="password" lay-verify="${name}" class="layui-input ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.textareaHtml = function()
        {
            html.push(`<textarea lay-verify="${name}" class="layui-textarea ${vclass}" name="${name}" id="${name}" placeholder="${placeholder}">${value}</textarea>`);
        }

        x.editorHtml = function()
        {
            html.push(`<textarea lay-verify="${name}" class="layui-textarea ${vclass}" name="${name}" id="${name}" placeholder="${placeholder}" style="height:280px;">${value}</textarea>`);
        }

        x.selectHtml = function()
        {
            html.push(`<select name="${name}" id="${name}" lay-search="" lay-filter="${name}">`);
            for(var i in list){
                var item = list[i];
                if(contain(value, item.key)){
                    html.push(`<option value="${item.key}" selected="">${item.text}</option>`);
                }
                else{
                    html.push(`<option value="${item.key}">${item.text}</option>`);
                }
            }
            html.push(`</select>`);
        }
        
        x.buttonThemeHtml = function()
        {
            list = [
                {"key": "layui-btn-green", "text": "墨绿"},
                {"key": "layui-btn-primary", "text": "银灰"},
                {"key": "layui-btn-normal", "text": "蓝色"},
                {"key": "layui-btn-warm", "text": "橙色"},
                {"key": "layui-btn-danger", "text": "赤色"}
            ];
            html.push(`<select name="${name}" id="${name}">`);
            for(var i in list){
                var item = list[i];
                if(contain(value, item.key)){
                    html.push(`<option value="${item.key}" selected="">${item.text}</option>`);
                }
                else{
                    html.push(`<option value="${item.key}">${item.text}</option>`);
                }
            }
            html.push(`</select>`);
        }

        x.radioHtml = function()
        {
            for(var i in list){
                var item = list[i];
                if(item.key == value){
                    html.push(`<input type="radio" name="${name}" value="${item.key}" title="${item.text}" lay-filter="${name}" checked>`);
                }
                else{
                    html.push(`<input type="radio" name="${name}" value="${item.key}" title="${item.text}" lay-filter="${name}">`);
                }
            }
        }

        x.checkboxHtml = function()
        {
            for(var i in list){
                var item = list[i];
                if(contain(value, item.key)){
                    html.push(`<input type="checkbox" name="${name}[]" value="${item.key}" lay-skin="primary" title="${item.text}" checked>`);
                }
                else{
                    html.push(`<input type="checkbox" name="${name}[]" value="${item.key}" lay-skin="primary" title="${item.text}">`);
                }
            }
        }

        x.checkboxBigHtml = function()
        {
            for(var i in list){
                var item = list[i];
                if(contain(value, item.key)){
                    html.push(`<input type="checkbox" name="${name}[]" value="${item.key}" title="${item.text}" checked>`);
                }
                else{
                    html.push(`<input type="checkbox" name="${name}[]" value="${item.key}" title="${item.text}">`);
                }
            }
        }

        x.transferHtml = function()
        {
            html.push(`<input type="hidden" name="${name}" id="${name}" value="${value}">`);
            html.push(`<div id="${name}_transfer"></div>`);
        }

        x.switchHtml = function()
        {
            var text = "";
            if(checked == "" || checked == "true"){
                text = `checked=""`;
            }
            else if(checked == "auto" && (value == "1" || value == "yes" || value == "true")){
                text = `checked=""`;
            }
            html.push(`<input type="checkbox" name="${name}" lay-skin="switch" lay-text="${openText}|${closeText}" ${text}>`);
        }

        x.colorHtml = function()
        {
            html.push(`<input type="text" lay-verify="${name}" class="layui-input ${vclass}" name="${name}" id="${name}" value="${value}" placeholder="${placeholder}">`);
        }

        x.submitHtml = function()
        {
            if(block){
                html.push(`<button type="submit" class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="default">${submit}</button>`);
            }
            else{
                html.push(`<button type="submit" class="layui-btn" lay-submit="" lay-filter="default">${submit}</button>`);
            }
            if(reset != ""){
                html.push(`<button type="reset" class="layui-btn layui-btn-primary">${reset}</button>`);
            }
        }
        
        x.iconHtml = function()
        {
            html.push(`<input type="hidden" name="${name}" id="${name}" value="${value}">`);
            html.push(`<div class="dry-box" id="${name}_box" data-id="${name}" style="cursor:pointer;"></div>`);
        }
        
        x.fileSelectHtml = function()
        {
            var code = `
            <div class="layui-card dry-skin-green">
                <div class="layui-card-header layui-unselect dry-fold pointer">面板</div>
                <div class="layui-card-body">
                    <input type="hidden" name="${name}" id="${name}" value="${value}">
                    <textarea class="layui-hide"></textarea>
                    <button type="button" class="layui-btn selectButton">选择</button>
                    <div class="box" id="imageShowBox-${name}" count="50" margin="10" width="150" height="150" style="margin-left:-10px;"></div>
                </div>
            </div>
            `;
            html.push(code);
        };

        function tag()
        {
            var data = that.parentNode.querySelector("textarea").innerHTML;
            data = JSON.parse(data);
            list = data.data.list;
            for(var i in list){
                var item = list[i];
                if(contain(value, item.key)){
                    if(!item.class){
                        item.class = "layui-bg-gray";
                    }
                    html.push(`<span class="layui-badge ${item.class}">${item.text}</span>`);
                }
            }
            doFinish();
        }

        function commonCallback(y)
        {
            var $ = y.jquery;
            var form = y.form;
            var laydate = y.laydate;
            var layer = y.layer;
            $("input.date").each(function(){
                laydate.render({elem: "#" + $(this).attr("id"), type: 'date', format: 'yyyy-MM-dd'});
            });
            $("input.time").each(function(){
                laydate.render({elem: "#" + $(this).attr("id"), type: 'time', format: 'HH:mm:ss'});
            });
            $("input.datetime").each(function(){
                laydate.render({elem: "#" + $(this).attr("id"), type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss'});
            });
            if(tip != ""){
                var theId = '#' + name + '_label';
                var index = null;
                $(theId).mouseover(function(){
                    index = layer.tips(tip, theId, {tips: 2, time: 10000});
                });
                $(theId).mouseout(function(){
                    layer.close(index);
                });
            }
            /*select改变时*/
            if(contain("select,selectOnly", role) && name != ""){
                form.on(`select(${name})`, function(t){
                    if(window["dryCommonSelectChange"]){
                        dryCommonSelectChange(t);
                    }
                });
            }
            form.render();
        }

        function transferCallback(y)
        {
            var transfer = y.transfer;
            var id = name + "_transfer";
            transfer.render({
                "elem": "#" + id,
                "title": ["待选择", "已选择"],
                parseData: function(rs){
                    return {
                        "value": rs.key,
                        "title": rs.text
                    };
                },
                "data": list,
                "value": value.split(","),
                "showSearch": true,
                "id": id,
                onchange: function(data, index){
                    var result = [];
                    var theList = transfer.getData(id);
                    for(var i = 0;i < theList.length;i++){
                        result.push(theList[i].value);
                    }
                    $$(name).value = result.join(",");
                }
            });
        }

        function colorCallback(y)
        {
            var colorpicker = y.colorpicker;
            var $ = y.jquery;
            colorpicker.render({
                elem: '#' + name + '-picker',
                color: value,
                predefine: true,
                done: function(color){
                    $('#' + name).val(color);
                }
            });
        }

        function editorCallback(y)
        {
            var $ = y.jquery;
            var layedit = y.layeditV2;
            var index = layedit.build(name);
            setInterval(function(){
                var e = $("#" + name);
                if(e.hasClass("layui-hide")){
                    layedit.sync(index);
                }
                else{
                    layedit.setContent(index, e.val(), false);
                }
            }, 1000);
            /**/
            $(".layedit-tool-html").click(function(){
                $(this).parent().parent().find("div.layui-layedit-iframe").toggleClass("layui-hide");
                $(this).parent().parent().parent().find("textarea").toggleClass("layui-hide");
            });
            /**/
        }
        
        function iconCallback(y)
        {
            var $ = y.jquery;
            var icon = y.icon;
            var css = `
            <style>
            .dry-box {
                border: 1px solid #e6e6e6;
                padding-left: 10px;
            }
            .dry-input-line-height {
                line-height: 38px;
            }
            .dry-icon-box {
                text-align: center;
                border: 1px solid #e6e6e6;
                margin-right: -1px;
                margin-bottom: -1px;
            }
            .dry-icon-item {
                line-height: 50px;
            }
            </style>
            `;
            $("body").append(css);
            icon.set(name + "_box");
        }
        
        function fileSelectCallback(y)
        {
            function success(json)
            {
                doHtml(json);
                setTextarea(json);
            }
        
            function doHtml(json)
            {
                var id = "imageShowBox-" + name;
                layui.laytpl(fileModule.fileSelectItem).render(json.data, function(htmlCode){
                    $("#" + id).html(htmlCode);
                    fileModule.setImageShow(id, false);
                });
            }
        
            /*把当前的数据存起来，方便打开选择时设置选中*/
            function setTextarea(json)
            {
                var theList = json.data.list;
                layui.each(theList, function(index, rs){
                    rs.addSort = index;
                    theList[index] = rs;
                });
                $("#" + name).parent().find("textarea").html(JSON.stringify(theList));
            }
            
            var layui = y;
            var $ = y.jquery;
            var fileModule = y.file;
            /*选择按钮点击时的操作*/
            $("#" + name).parent().find(".selectButton").click(function(){
                fileModule.doSelectButton(name, iframeUrl);
            });
            /**/
            if(value == ""){
                return false;
            }
            var theData = {
                "dataIn": value
            };
            post(url, toFormData(theData), success, null);
        }

        function createWrapStart()
        {
            html.push(`<div class="layui-form-item">`);
            if(block){
                if(role != "submit"){
                    html.push(`<div class="layui-input-block" style="margin-left:0;">${label}</div>`);
                }
            }
            else{
                html.push(`<label class="layui-form-label" id="${name}_label">${label}</label>`);
            }
            if(help != "" || role == "color"){
                html.push(`<div class="layui-input-inline">`);
            }
            else{
                if(block){
                    html.push(`<div class="layui-input-block" style="margin-left:0;">`);
                }
                else{
                    html.push(`<div class="layui-input-block">`);
                }
            }
        }

        function createWrapEnd()
        {
            html.push(`</div>`);
            if(role == "color"){
                html.push(`<div id="${name}-picker"></div>`);
            }
            if(help != ""){
                html.push(`<div class="layui-form-mid layui-word-aux">${help}</div>`);
            }
            html.push(`</div>`);
        }

        function createHtml()
        {
            createWrapStart();
            var f = role + "Html";
            x[f]();
            createWrapEnd();
        }

        function doFinish()
        {
            if(ref == ""){
                ref = getUnique();
                that.insertAdjacentHTML("afterend", `<div id="${ref}"></div>`);
            }
            $$(ref).innerHTML = html.join("");
            if(role == "transfer"){
                runCallback(transferCallback);
            }
            else if(role == "color"){
                runCallback(colorCallback);
            }
            else if(role == "editor"){
                runCallback(editorCallback);
            }
            else if(role == "icon"){
                runCallback(iconCallback);
            }
            else if(role == "fileSelect"){
                runCallback(fileSelectCallback);
            }
            runCallback(commonCallback);
        }

        function runCallback(p)
        {
            var f = window[callback];
            if(!f){
                setTimeout(function(){
                    runCallback(p);
                }, 500);
            }
            else{
                f(p);
                that.setAttribute("ok", "1");
                if(contain("selectOnly", role) && window["dryCommonReady"]){
                    dryCommonReady(that);
                }
            }
        }
        
        if(value == ""){
            var textareaList = that.getElementsByTagName("textarea");
            if(textareaList.length){
                value = textareaList[0].innerHTML;
            }
        }
        /*回调函数*/
        if(callback == ""){
            callback = "dryCallback";
        }
        /*需要一开始从变量或者接口获取数据的组件*/
        var getDataRole = ["select", "radio", "checkbox", "checkboxBig", "transfer", "selectOnly"].join(",");
        if(contain(getDataRole, role)){
            if(variable != ""){
                var temp = window[variable];
                temp = insert(temp);
                data = {
                    data: {
                        list: temp
                    }
                };
                list = data.data.list;
                direct();
            }
            else{
                fetch(url).then(success).catch(fail);
            }
        }
        else{
            if(role == "tag"){
                tag();
            }
            else{
                direct();
            }
        }
        /**/
    }
};
window.customElements.define('dry-common', dryCommon);